package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("test2")
public class TestController2 {
    //获取参数

    //1.获取单个参数（从url参数部分获取）
    @RequestMapping("/getname")
    public String getName(HttpServletRequest request){
        return "name："+request.getParameter("name");
    }

    @RequestMapping("/getname2")
    public String getName2(String name){
        return "name2："+name;
    }

    //2.获取多个参数（从url参数部分获取）
    @RequestMapping("/getname3")
    public String getName3(String name,Integer age){
        return "name："+name+"，age："+age;
    }

    //3.从url非参数部分获取参数
    @RequestMapping("/detail/{aid}")
    public Integer detail(@PathVariable("aid") Integer aid){
        return aid;
    }

    @RequestMapping("/detail2/{aid}/{name}")
    public String detail2(@PathVariable("aid") Integer aid,@PathVariable("name") String name){
        return "aid："+aid+" ,name："+name;
    }


    //获取文件
    @RequestMapping("/upload")
    public String upload(@RequestPart("myfile") MultipartFile file) throws IOException {
        //1.生成一个唯一的id（UUID）
        String name= UUID.randomUUID().toString().replace("-","");
        //2.得到源文件的后缀名
        name+=(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));

        String path="C:\\Users\\16050\\Desktop\\"+name;
        //保存文件
        file.transferTo(new File(path));
        return path;
    }

    //获取cookie
    @RequestMapping("/getcookie")
    public String getCookie(@CookieValue(value = "java",required=false)String ck){
        return ck;
    }

    //获取Session
    @RequestMapping("/getsession")
    public String getSession(@SessionAttribute(required = false,value = "session_key")String name){
        return name;
    }

    //获取Header
    @RequestMapping("/header")
    public String header(@RequestHeader("user_agent") String header){
        return header;
    }
}
